package net.ojbk.timeAxis.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import net.ojbk.timeAxis.service.TimeAxisService;

/**
 * Servlet implementation class timeAxisServlet
 */
@WebServlet("/timeAxisServlet")
public class timeAxisServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public timeAxisServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("--------timeAxis----------");
		response.setContentType("text/html;charset=utf-8");
	    response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session=request.getSession();
	    // 前奏 ↑
		String userId = (String)session.getAttribute("userId");
		if (userId == null || session.getAttribute("login") == null || userId.equals("") || !(boolean)session.getAttribute("login")) { // 未登录 或 错误
			return ;
		}
		// 判断基本权限 ↑
		TimeAxisService service = new TimeAxisService();
		
	    String type = request.getParameter("type"); // modifyMsgPw 、 
	    Map<String,Object>map=new HashMap<String,Object>(); // 够着 json
	   
	    if (type.equals("modifyMsgPw")) {
		    String axisId = request.getParameter("axisId");
		    String newPw = request.getParameter("newPw");
	    	if (!service.CheckmodifyMsgPw(userId, axisId))
	    		map.put("status", false);
	    	else if (service.modifyMsgPw(axisId, newPw) == 1)
	    		map.put("status", true);
	    	else
	    		map.put("status", false);
	    } else {
	    	map.put("status", false);
	    }
		// 写出到 json
		JSONObject json=new JSONObject(map); // 转化为 json对象
		out.write(json.toString());
		out.flush();
		System.out.println(json.toString());
	    
	}
}
